<template>
  <div class="detail-container">
    <!-- 顶部导航 -->
    <div class="detail-header">
      <div class="header-nav">
        <van-icon name="arrow-left" class="back-icon" @click="goBack" />
        <div class="header-title">详情</div>
      </div>
    </div>

    <!-- 渐变背景区域 -->
    <div class="gradient-section">
      <!-- 文本信息区域 -->
      <div class="text-container">
        <div class="header-title" v-if="detailData.createName">
          {{ detailData.createName }}提交的合同审批
        </div>
        <div class="company—title">北京君初律师事务所</div>
        <div class="company-handle" :class="getStatusClass()">
          {{ getHandleText() }}
        </div>
      </div>
      <!-- 页面图标和状态图标 -->
      <div class="icon-container">
        <div class="main-icon">
          <img
            src="@/assets/homeOther/country_page_icon.png"
            alt="详情图标"
            class="icon-img"
          />
          <!-- 状态图标 -->
          <div class="status-badge" v-if="getStatusIcon()">
            <img
              :src="getStatusIcon()"
              :alt="getStatusText()"
              class="status-img"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 详情内容 -->
    <div class="detail-content">
      <!-- 基本信息 -->
      <div class="info-section">
        <!-- <div class="section-title">基本信息</div> -->
        <div class="info-list">
          <div class="info-item">
            <div class="info-label">审批编号</div>
            <div class="info-value">{{ detailData.no || detailData.id }}</div>
          </div>
          <!-- <div class="info-item">
            <div class="info-label">申请人</div>
            <div class="info-value">{{ detailData.name }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">申请时间</div>
            <div class="info-value">{{ detailData.createDate ? formatShortDateTime(detailData.createDate) : '' }}</div>
          </div> -->
          <div class="info-item">
            <div class="info-label">所在部门</div>
            <div class="info-value">
              {{ detailData.department || "暂无部门" }}
            </div>
          </div>
        </div>
      </div>

      <!-- 详细信息 -->
      <div class="detail-section">
        <div class="section-title">签署信息</div>
        <div class="detail-list">
          <div class="detail-item" v-if="detailData.signingMethod">
            <div class="detail-label">签署方式</div>
            <div class="detail-value">
              {{ getSignMethodName(detailData.signingMethod) }}
            </div>
          </div>
          <div class="detail-item" v-if="detailData.signTime">
            <div class="detail-label">签署日期</div>
            <div class="detail-value">
              {{ detailData.signTime.replace(/\//g, "-") }}
            </div>
          </div>
          <div class="detail-item" v-if="detailData.sealType">
            <div class="detail-label">印章类型</div>
            <div class="detail-value">
              {{ getSealTypeName(detailData.sealType) }}
            </div>
          </div>
          <!-- <div class="detail-item" v-if="detailData.contractNote">
            <div class="detail-label">合同说明</div>
            <div class="detail-value">{{ detailData.contractNote }}</div>
          </div> -->
        </div>
      </div>
      <!-- 基本信息 -->
      <div class="detail-section">
        <div class="section-title">基本信息</div>
        <div class="detail-list">
          <div class="detail-item" v-if="detailData.name">
            <div class="detail-label">合同名称</div>
            <div class="detail-value">{{ detailData.name }}</div>
          </div>
          <div class="detail-item" v-if="detailData.no">
            <div class="detail-label">合同编号</div>
            <div class="detail-value">{{ detailData.no }}</div>
          </div>


          <div class="detail-item" v-if="detailFileList.length">
            <div class="detail-label">合同附件</div>
            <div class="detail-value">
              <VantUploader
                v-model="detailFileList"
                :showUploadButton="false"
                :deletable="false"
                :readonly="true"
              />
            </div>
          </div>
          <div class="detail-item" v-if="detailData.amountType">
            <div class="detail-label">金额类型</div>
            <div class="detail-value">
              {{ getAmountTypeName(detailData.amountType) }}
            </div>
          </div>

          <div class="detail-item" v-if="detailData.contractTermType">
            <div class="detail-label">合同期限类型</div>
            <div class="detail-value">
              {{ getTermTypeName(detailData.contractTermType) }}
            </div>
          </div>
          <div class="detail-item" v-if="detailData.contractNote">
            <div class="detail-label">合同说明</div>
            <div class="detail-value">{{ detailData.contractNote }}</div>
          </div>
        </div>
      </div>
      <!-- 合同正文 -->

      <!-- 相对信息 -->
      <div class="detail-section">
        <div class="section-title">相对方信息</div>
        <div class="detail-list">
          <div class="message-title">委托方信息</div>
          <div class="detail-item" v-if="detailData.clientName">
            <div class="detail-label">委托人名称</div>
            <div class="detail-value">{{ detailData.clientName }}</div>
          </div>
          <div class="detail-item" v-if="detailData.clientType">
            <div class="detail-label">委托人类型</div>
            <div class="detail-value">
              {{ getclientTypeOptionsTypeName(detailData.clientType) }}
            </div>
          </div>

          <div class="message-title">对方信息</div>
          <div class="detail-item" v-if="detailData.otherEntityName">
            <div class="detail-label">对方主体名称</div>
            <div class="detail-value">{{ detailData.otherEntityName }}</div>
          </div>
          <div class="detail-item" v-if="detailData.otherCharge">
            <div class="detail-label">对方负责人</div>
            <div class="detail-value">{{ detailData.otherCharge }}</div>
          </div>
        </div>
      </div>

      <!-- 审批流程 -->
      <div class="approval-section">
        <div class="section-title">流程</div>
        <div class="approval-list">
          <div
            v-for="(step, index) in detailData.approvalSteps || []"
            :key="index"
            class="approval-step"
            :class="{ current: step.isCurrent, completed: step.isCompleted }"
          >
            <!-- 左侧：头像和审批信息 -->
            <div class="step-left">
              <div class="step-avatar">
                <AvatarDisplay :url="step.avatarUrl" :name="step.userName" />
                <!-- 状态图标 -->
                <div
                  class="step-status"
                  v-if="step.isCompleted || step.isCurrent"
                >
                  <van-icon
                    :name="step.isCompleted ? 'success' : 'ellipsis'"
                    :color="step.isCompleted ? '#FFFFFF' : '#FFFFFF'"
                    :style="{
                      backgroundColor: step.isCompleted ? '#4CAF50' : '#FF9200',
                      borderRadius: '50%',
                      padding: '2px',
                      width: '16px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }"
                    size="10px"
                  />
                </div>
              </div>
              <div class="step-info">
                <div class="step-title">{{ step.title }}</div>
                <div class="step-user">{{ step.user }}</div>
              </div>
            </div>
            <!-- 右侧：时间 -->
            <div class="step-right">
              <div class="step-time" v-if="step.time">{{ step.time }}</div>
            </div>
            <!-- 连接线 -->
            <div
              class="step-line"
              v-if="index < (detailData.approvalSteps || []).length - 1"
            ></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div
      class="action-buttons"
      v-if="
        (shouldShowRevokeButton() &&
          detailData.firstApproverState == 0 &&
          detailData.secondApproverState == 0 &&
          detailData.nowState === 0) ||
        shouldShowApprovalButtons()
      "
    >
      <van-button
        v-if="
          shouldShowRevokeButton() &&
          detailData.firstApproverState == 0 &&
          detailData.secondApproverState == 0 &&
          detailData.nowState === 0
        "
        class="action-btn revoke-btn"
        @click="showRevokeDialog"
        :loading="revokeLoading"
        :disabled="revokeLoading || approveLoading || rejectLoading"
        plain
      >
        <van-icon v-if="!revokeLoading" name="revoke" class="btn-icon" />
        撤销
      </van-button>
      <van-button
        v-if="shouldShowApprovalButtons()"
        class="action-btn reject-btn"
        @click="showRejectDialog"
        :loading="rejectLoading"
        :disabled="revokeLoading || approveLoading || rejectLoading"
        plain
      >
        <van-icon v-if="!rejectLoading" name="close" class="btn-icon" />
        拒绝
      </van-button>
      <van-button
        v-if="shouldShowApprovalButtons()"
        class="action-btn approve-btn"
        @click="showApproveDialog"
        :loading="approveLoading"
        :disabled="revokeLoading || approveLoading || rejectLoading"
        plain
      >
        <van-icon v-if="!approveLoading" name="success" class="btn-icon" />
        同意
      </van-button>
    </div>

    <!-- 通用确认弹窗 -->
    <van-dialog
      v-model:show="showConfirmDialog"
      show-cancel-button
      :confirm-button-text="dialogConfig.confirmText"
      cancel-button-text="取消"
      @confirm="handleConfirm"
      @cancel="handleCancel"
    >
      <div class="dialog-content">
        <div class="dialog-text">{{ dialogConfig.message }}</div>
        <van-field
          v-model="remark"
          type="textarea"
          :placeholder="dialogConfig.placeholder"
          rows="3"
          maxlength="200"
          show-word-limit
          required
        />
      </div>
    </van-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { showToast } from "vant";
import { queryDetailApi, dealContractApi } from "@/api/home";
import { getUserPicture, revokeContract } from "@/api/contract";
import { storage } from "@/utils/storage";
import { request, API_BASE_URL } from "@/utils/http";
import { refreshTokenApi } from "@/api/index";
import {
  getTermTypeName,
  getSignMethodName,
  getSealTypeName,
  getAmountTypeName,
  getclientTypeOptionsTypeName,
} from "@/utils/enums";
import { formatShortDateTime } from "@/utils/formatters";
import { getDetailBackTarget, useSmartDetailBack } from "@/utils/navigation";
import pictureImg from "@/assets/homeOther/picture.png";
import pictureOneImg from "@/assets/homeOther/sm_picture.png";
import pictureTwoImg from "@/assets/homeOther/picture_two.png";
// 导入默认头像
import defaultAvatar from "@/assets/homeOther/default_avatar.svg";
import AvatarDisplay from "@/components/UserAvatar/AvatarDisplay.vue";
import VantUploader from "@/components/UploadFiled/VantUploader.vue";
import { showImagePreview } from "vant";

// 路由实例
const router = useRouter();
const route = useRoute();

// 启用智能返回：根据来源(home/approvals/add)处理左滑/系统返回
useSmartDetailBack(router, route);

// 详情数据类型定义
interface ApprovalStep {
  title: string;
  user: string;
  userName: string; // 用户名用于头像组件
  time?: string;
  avatar?: any;
  avatarUrl?: string; // 头像URL用于头像组件
  isCurrent: boolean;
  isCompleted: boolean;
}

interface DetailData {
  id: string;
  name: string;
  createDate: string | null;
  createId: number;
  no?: string | null;
  department: string;

  // 审批相关字段
  firstApprover: number;
  secondApprover: number;
  thirdApprover: number;
  nowApprover: number;
  nowState?: number;
  firstApproverState: number;
  secondApproverState: number;
  thirdApproverState: number;
  approveDate?: string | null;

  // 审批人头像URL字段
  firstApproverUrl?: string | null;
  secondApproverUrl?: string | null;
  thirdApproverUrl?: string | null;

  // 新增字段
  createName?: string | null;
  createUrl?: string | null;
  firstApproverName?: string | null;
  secondApproverName?: string | null;
  thirdApproverName?: string | null;

  // 合同特有字段
  contractTermType?: string | null;
  contractNote?: string | null;
  clientName?: string | null;
  otherEntityName?: string | null;
  clientType?: string | null;
  otherCharge?: string | null;
  signingMethod?: string | null;
  signTime?: string | null;
  sealType?: string | null;
  amountType?: string | null; // 金额类型字段

  // 前端显示用字段
  status?: "revoked" | "passed" | "rejected";
  approvalSteps?: ApprovalStep[];
}

// 加载状态
const loading = ref(false);
const revokeLoading = ref(false);
const approveLoading = ref(false);
const rejectLoading = ref(false);

// 通用弹窗状态
const showConfirmDialog = ref(false);
const remark = ref("");
const currentAction = ref<"revoke" | "reject" | "approve">("approve");

// 弹窗配置
const dialogConfig = ref({
  title: "",
  message: "",
  confirmText: "",
  placeholder: "",
});

// 当前登录用户ID
const currentUserId = ref<number | null>(null);

// 获取当前登录用户ID
const getCurrentUserId = () => {
  try {
    const userInfo = storage.getUserInfo();
    if (userInfo) {
      return userInfo.id || null;
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
  return null;
};

// 详情数据
const detailData = reactive<DetailData>({
  id: "",
  name: "",
  createDate: null,
  createId: 0,
  no: null,
  department: "",
  firstApprover: 0,
  secondApprover: 0,
  thirdApprover: 0,
  nowApprover: 0,
  nowState: 0,
  firstApproverState: 0,
  secondApproverState: 0,
  thirdApproverState: 0,
  approveDate: null,
  contractTermType: null,
  contractNote: null,
  clientName: null,
  otherEntityName: null,
  clientType: null,
  otherCharge: null,
  signingMethod: null,
  signTime: null,
  sealType: null,
  status: "passed",
  approvalSteps: [],
});

// 获取状态图标
const getStatusIcon = () => {
  const nowState = detailData.nowState || 0;

  if (nowState === 0) {
    // 0是等待审批-没有图标
    return "";
  } else if (nowState === 1) {
    // 1是审批完成
    return "/src/assets/homeOther/passed.png";
  } else if (nowState === -1) {
    // -1是已撤销
    return "/src/assets/homeOther/revoked_iocn.png";
  } else if (nowState === 2) {
    // 2是已拒绝
    return "/src/assets/homeOther/rejected.png";
  }
  return "";
};

// 获取状态文本
const getStatusText = () => {
  const nowState = detailData.nowState || 0;

  if (nowState === 0) {
    return "等待审批";
  } else if (nowState === 1) {
    return "已通过";
  } else if (nowState === -1) {
    return "已撤销";
  } else if (nowState === 2) {
    return "已拒绝";
  }
  return "等待审批";
};

// 获取状态样式类
const getStatusClass = () => {
  const nowState = detailData.nowState || 0;

  switch (nowState) {
    case 0:
      return "status-pending"; // 等待审批
    case 1:
      return "status-completed"; // 审批完成
    case -1:
      return "status-revoked"; // 已撤销
    case 2:
      return "status-rejected"; // 已拒绝
    default:
      return "status-pending"; // 默认等待审批
  }
};

// 获取处理状态文本
const getHandleText = () => {
  const nowState = detailData.nowState || 0;

  if (nowState === 0) {
    // 等待审批状态，根据nowApprover匹配对应的审批人姓名
    let approverName = "";

    if (
      detailData.nowApprover === detailData.firstApprover &&
      detailData.firstApprover !== -1
    ) {
      approverName = detailData.firstApproverName || "";
    } else if (
      detailData.nowApprover === detailData.secondApprover &&
      detailData.secondApprover !== -1
    ) {
      approverName = detailData.secondApproverName || "";
    } else if (
      detailData.nowApprover === detailData.thirdApprover &&
      detailData.thirdApprover !== -1
    ) {
      approverName = detailData.thirdApproverName || "";
    }

    return approverName ? `等待${approverName}处理` : "等待处理";
  } else if (nowState === 1) {
    return "审批完成";
  } else if (nowState === -1) {
    return "已撤销";
  } else if (nowState === 2) {
    return "审批拒绝";
  }
  return "等待处理";
};

// 返回：根据来源(home/approvals/add)智能跳转
const goBack = () => {
  const target = getDetailBackTarget(route);
  router.push(target);
};
// 加载用户头像
const loadUserAvatar = async (url: string) => {
  if (!url) return defaultAvatar;

  try {
    const blob = await getUserPicture(url);
    return URL.createObjectURL(blob);
  } catch (error) {
    console.error("加载头像失败:", error);
    return defaultAvatar;
  }
};

// 获取用户头像URL
const getAvatarUrl = (user: string) => {
  // 这里可以根据用户信息生成头像URL，或者从用户信息中获取
  // 目前使用默认头像
  return defaultAvatar;
};
// 获取详情数据
const fetchDetailData = async () => {
  const id = route.params.id as string;
  const type = route.query.type as string;

  if (!id || !type) {
    showToast("页面参数错误，请重新进入");
    setTimeout(() => {
      router.push("/contract");
    }, 1500);
    return;
  }

  try {
    loading.value = true;
    const response = await queryDetailApi(id, type);

    if (response.code === 0) {
      // 更新详情数据
      Object.assign(detailData, response.data);

      // 构建审批流程数据
      await buildApprovalSteps();

      // showToast('数据加载完成')
    } else {
      showToast(response.msg || "数据加载失败");
    }
  } catch (error) {
    showToast("数据加载失败");
    console.error("获取详情数据失败:", error);
  } finally {
    loading.value = false;
  }
};

// 构建审批流程数据
const buildApprovalSteps = async () => {
  const steps: ApprovalStep[] = [];
  const nowState = detailData.nowState || 0;

  // 发起申请步骤
  const createAvatar = detailData.createUrl
    ? await loadUserAvatar(detailData.createUrl)
    : pictureImg;

  // 添加发起申请步骤
  steps.push({
    title: "发起申请",
    user: `申请人: ${detailData.createName || detailData.name}`,
    userName: detailData.createName || detailData.name || "",
    time: detailData.createDate
      ? formatShortDateTime(detailData.createDate)
      : "",
    avatar: createAvatar,
    avatarUrl: detailData.createUrl || "",
    isCurrent: false,
    isCompleted: true,
  });

  // 如果是已撤销状态，添加撤销步骤，不显示审批人
  if (nowState === -1) {
    steps.push({
      title: "已撤销",
      user: `${detailData.createName || detailData.name} (已撤销)`,
      userName: detailData.createName || detailData.name || "",
      time: "", // 撤销时间可以根据实际需求添加
      avatar: createAvatar,
      avatarUrl: detailData.createUrl || "",
      isCurrent: false,
      isCompleted: false,
    });
    detailData.approvalSteps = steps;
    return;
  }

  // 获取审批状态文本
  const getApprovalStatusText = (state: number) => {
    switch (state) {
      case 0:
        return "未审批";
      case 1:
        return "已审批";
      case -1:
        return "已拒绝";
      default:
        return "未审批";
    }
  };

  // 审批人信息数组，包含所有可能的审批人
  const approvers = [
    {
      id: detailData.firstApprover,
      name: detailData.firstApproverName,
      url: detailData.firstApproverUrl,
      state: detailData.firstApproverState,
      defaultAvatar: pictureOneImg,
    },
    {
      id: detailData.secondApprover,
      name: detailData.secondApproverName,
      url: detailData.secondApproverUrl,
      state: detailData.secondApproverState,
      defaultAvatar: pictureTwoImg,
    },
    {
      id: detailData.thirdApprover,
      name: detailData.thirdApproverName,
      url: detailData.thirdApproverUrl,
      state: detailData.thirdApproverState,
      defaultAvatar: defaultAvatar,
    },
  ];

  // 遍历审批人，实现流程中断逻辑
  let shouldStop = false;
  for (const approver of approvers) {
    // 如果已经遇到失败步骤，后续步骤都不显示
    if (shouldStop) break;

    // 只显示有效的审批人（ID存在且不为-1）
    if (approver.id && approver.id !== -1) {
      const avatar = approver.url
        ? await loadUserAvatar(approver.url)
        : approver.defaultAvatar;
      const statusText = getApprovalStatusText(approver.state);

      steps.push({
        title: "审批人",
        user: `${approver.name || ""} (${statusText})`,
        userName: approver.name || "",
        time:
          approver.state === 1 && detailData.approveDate
            ? formatShortDateTime(detailData.approveDate)
            : "",
        avatar: avatar,
        avatarUrl: approver.url || "",
        isCurrent:
          approver.state === 0 && detailData.nowApprover === approver.id,
        isCompleted: approver.state === 1,
      });

      // 如果当前审批人已拒绝，标记需要停止后续步骤
      if (approver.state === -1) {
        shouldStop = true;
      }
    }
  }

  detailData.approvalSteps = steps;
};

// ================= 附件解析与预览 =================
// 将后端返回的字符串 attachmentUrl 解析为数组
const attachmentList = computed(() => {
  const raw = (detailData as any).attachmentUrl || "";
  if (!raw || typeof raw !== "string")
    return [] as Array<{ path: string; name: string; ext: string }>;
  return raw
    .split(",")
    .map((s: string) => s.trim())
    .filter((s: string) => !!s)
    .map((path: string) => {
      const normalized = path.replace(/\\/g, "/");
      const name = normalized.split("/").pop() || "附件";
      const lower = (name || "").toLowerCase();
      const ext = lower.includes(".") ? lower.split(".").pop() || "" : "";
      return { path: normalized, name, ext };
    });
});

const detailFileList = ref<Array<any>>([]);
watch(
  attachmentList,
  (list) => {
    const imgExts = ["jpg", "jpeg", "png", "gif", "bmp", "webp"];
    detailFileList.value = (list || []).map((att, idx) => {
      const ext =
        (att.name || att.path || "").toLowerCase().split(".").pop() || "";
      const isImg = imgExts.includes(ext);
      const path = att.path;
      const isAbs = /^(https?:|data:|blob:)/i.test(path);
      const isRoot = /^\//.test(path);
      const url = isImg
        ? isAbs
          ? path
          : `${API_BASE_URL}${isRoot ? path : `/${path}`}`
        : undefined;
      return {
        id: `detail-${idx}`,
        name: att.name,
        serverPath: att.path,
        uploadedPath: att.path,
        status: "done",
        file: null,
        isImage: isImg,
        url,
      };
    });
  },
  { immediate: true }
);
const imageExts = ["jpg", "jpeg", "png", "gif", "bmp", "webp"];
const getAttIconClass = (att: { ext: string }) => {
  const e = (att.ext || "").toLowerCase();
  if (imageExts.includes(e)) return "img";
  if (e === "pdf") return "pdf";
  if (e === "docx" || e === "doc") return "docx";
  if (e === "xls" || e === "xlsx") return "xls";
  return "file";
};
const getAttIconText = (att: { ext: string }) => {
  const e = (att.ext || "").toUpperCase();
  if (imageExts.includes(e.toLowerCase())) return "IMG";
  if (e === "PDF") return "PDF";
  if (e === "DOCX" || e === "DOC") return "W";
  if (e === "XLS" || e === "XLSX") return "XLS";
  return "FILE";
};

// 预览：图片用 Vant 的图片预览，其它文件用浏览器新窗口打开
// 与上传附件组件一致的预览逻辑：图片直接预览，其它跳转到统一的文件预览页
const normalizeServerPath = (raw: string) => {
  if (!raw || typeof raw !== "string") return "";
  try {
    return raw.replace(/\\/g, "/");
  } catch {
    return raw;
  }
};

const fetchBlobUrlWithRefresh = async (filePath: string) => {
  const makeRequest = async () => {
    const response = await request(`${API_BASE_URL}/OA/file/download`, {
      method: "GET",
      params: { path: filePath },
      responseType: "blob",
    });
    return response;
  };

  const resp = await makeRequest();
  const headers = (resp as any)?.headers || {};
  const contentType = headers["content-type"] || headers["Content-Type"] || "";
  const blobData = (resp as any)?.data ? (resp as any).data : resp;

  if (String(contentType).toLowerCase().includes("application/json")) {
    try {
      const text = await (blobData as Blob).text();
      const json = JSON.parse(text);
      const msg = json?.msg || json?.message || "";
      if (json?.code === 401 || /token/i.test(msg)) {
        try {
          const refreshResp = await refreshTokenApi();
          const newToken = refreshResp?.data?.accessToken;
          if (newToken) {
            storage.setItem("accessToken", newToken);
            const retried = await makeRequest();
            const retriedBlobData = (retried as any)?.data
              ? (retried as any).data
              : retried;
            const blob =
              retriedBlobData instanceof Blob
                ? retriedBlobData
                : new Blob([retriedBlobData]);
            return window.URL.createObjectURL(blob);
          }
          throw new Error("刷新token失败，请重新登录");
        } catch (e) {
          throw new Error(json?.msg || "登录已过期，请重新登录");
        }
      }
      const blob = new Blob([text], { type: "text/plain" });
      return window.URL.createObjectURL(blob);
    } catch (e) {
      const blob =
        blobData instanceof Blob ? blobData : new Blob([blobData as any]);
      return window.URL.createObjectURL(blob);
    }
  }

  const blob =
    blobData instanceof Blob ? blobData : new Blob([blobData as any]);
  return window.URL.createObjectURL(blob);
};

const previewAttachment = async (att: {
  path: string;
  name: string;
  ext: string;
}) => {
  try {
    const path = normalizeServerPath(att.path);
    const ext = (att.ext || "").toLowerCase();
    const isImage = imageExts.includes(ext);

    if (isImage) {
      const blobUrl = await fetchBlobUrlWithRefresh(path);
      if (!blobUrl) {
        showToast("预览地址获取失败");
        return;
      }
      showImagePreview([blobUrl]);
      return;
    }

    router.push({
      path: "/file-preview",
      query: {
        path: encodeURIComponent(path),
        name: encodeURIComponent(att.name || ""),
      },
    });
  } catch (e: any) {
    console.error("附件预览失败:", e);
    const msg = e?.message || "";
    if (msg.includes("登录") || /401/.test(msg) || /token/.test(msg)) {
      showToast(msg.includes("登录") ? msg : "登录已过期，请重新登录");
      const currentPath = window.location.hash.slice(1);
      setTimeout(() => {
        window.location.href = `/#/login?redirect=${encodeURIComponent(
          currentPath || "/"
        )}`;
      }, 1200);
    } else {
      showToast("预览失败，请稍后重试");
    }
  }
};

// 显示弹窗的方法
const showRevokeDialog = () => {
  currentAction.value = "revoke";
  dialogConfig.value = {
    title: "撤销申请",
    message: "确认要撤销此申请吗？",
    confirmText: "确认撤销",
    placeholder: "请输入撤销原因",
  };
  remark.value = "";
  showConfirmDialog.value = true;
};

const showRejectDialog = () => {
  currentAction.value = "reject";
  dialogConfig.value = {
    title: "拒绝申请",
    message: "确认要拒绝此申请吗？",
    confirmText: "确认拒绝",
    placeholder: "请输入拒绝原因",
  };
  remark.value = "";
  showConfirmDialog.value = true;
};

const showApproveDialog = () => {
  currentAction.value = "approve";
  dialogConfig.value = {
    title: "同意申请",
    message: "确认要同意此申请吗？",
    confirmText: "确认同意",
    placeholder: "请输入同意原因",
  };
  remark.value = "";
  showConfirmDialog.value = true;
};

// 通用取消操作
const handleCancel = () => {
  showConfirmDialog.value = false;
  remark.value = "";
};

// 通用确认操作
const handleConfirm = async () => {
  // if (!remark.value.trim()) {
  //   showToast('请输入原因')
  //   return
  // }

  switch (currentAction.value) {
    case "revoke":
      await handleRevoke();
      break;
    case "reject":
      await handleReject();
      break;
    case "approve":
      await handleApprove();
      break;
  }
};

// 按钮事件处理
const handleRevoke = async () => {
  try {
    revokeLoading.value = true;
    showConfirmDialog.value = false;

    const result = await revokeContract({
      id: detailData.id,
      type: "1",
      remark: remark.value.trim(),
    });

    if (result.code === 0) {
      showToast("撤销成功");
      remark.value = "";

      const fromApprovals = route.query.from === "approvals";
      const fromAdd = route.query.from === "add";

      if (fromApprovals || fromAdd) {
        router.push("/approvals");
      } else {
        router.push("/home");
      }
    } else {
      showToast(result.msg || "撤销失败");
    }
  } catch (error) {
    showToast("撤销失败，请重试");
    console.error("撤销操作失败:", error);
  } finally {
    revokeLoading.value = false;
  }
};

const handleReject = async () => {
  try {
    rejectLoading.value = true;
    showConfirmDialog.value = false;
    const result = await dealContractApi(
      detailData.id,
      false,
      remark.value.trim()
    );

    if (result.code === 0) {
      showToast("拒绝成功");
      remark.value = "";

      const fromApprovals = route.query.from === "approvals";
      const fromAdd = route.query.from === "add";

      if (fromApprovals || fromAdd) {
        router.push("/approvals");
      } else {
        router.push("/home");
      }
    } else {
      showToast(result.msg || "拒绝失败");
    }
  } catch (error) {
    showToast("拒绝失败，请重试");
    console.error("拒绝操作失败:", error);
  } finally {
    rejectLoading.value = false;
  }
};

const handleApprove = async () => {
  try {
    approveLoading.value = true;
    showConfirmDialog.value = false;

    const result = await dealContractApi(
      detailData.id,
      true,
      remark.value.trim()
    );

    if (result.code === 0) {
      showToast("同意成功");
      remark.value = "";

      const fromApprovals = route.query.from === "approvals";
      const fromAdd = route.query.from === "add";

      if (fromApprovals || fromAdd) {
        router.push("/approvals");
      } else {
        router.push("/home");
      }
    } else {
      showToast(result.msg || "同意失败");
    }
  } catch (error) {
    showToast("同意失败，请重试");
    console.error("同意操作失败:", error);
  } finally {
    approveLoading.value = false;
  }
};

// 获取当前登录用户ID
const initCurrentUserId = () => {
  try {
    const userInfo = storage.getUserInfo();
    if (userInfo) {
      currentUserId.value = userInfo.id || null;
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
};

// 判断是否显示撤销按钮
const shouldShowRevokeButton = () => {
  console.log(currentUserId.value, "currentUserId.value", detailData.createId);
  return (
    currentUserId.value !== null && currentUserId.value === detailData.createId
  );
};

// 判断当前用户是否为当前审批人
const isCurrentApprover = () => {
  if (currentUserId.value === null || !detailData.nowApprover) {
    return false;
  }

  // 检查当前用户ID是否与nowApprover匹配
  if (currentUserId.value !== detailData.nowApprover) {
    return false;
  }

  // 检查nowApprover是否在审批人列表中
  const approvers = [
    detailData.firstApprover,
    detailData.secondApprover,
    detailData.thirdApprover,
  ];
  return (
    approvers.includes(detailData.nowApprover) && detailData.nowApprover !== -1
  );
};

// 判断是否显示审批按钮（拒绝、同意）
const shouldShowApprovalButtons = () => {
  return detailData.nowState === 0 && isCurrentApprover();
};

// 页面加载
onMounted(() => {
  // 获取当前登录用户ID
  currentUserId.value = getCurrentUserId();
  fetchDetailData();
});

// 导出响应式变量和方法供模板使用
defineExpose({
  loading,
  revokeLoading,
  approveLoading,
  rejectLoading,
  showConfirmDialog,
  dialogConfig,
  remark,
  currentAction,
  detailData,
  getStatusIcon,
  getStatusText,
  getHandleText,
  goBack,
  showRevokeDialog,
  showRejectDialog,
  showApproveDialog,
  handleCancel,
  handleConfirm,
  handleRevoke,
  handleReject,
  handleApprove,
  shouldShowRevokeButton,
  isCurrentApprover,
  shouldShowApprovalButtons,
});
</script>

<style lang="scss" scoped>
@import url("./style/index.scss");

// 弹窗样式
.dialog-content {
  padding: 16px;

  .dialog-text {
    margin-bottom: 16px;
    font-size: 14px;
    color: #323233;
    text-align: center;
  }

  :deep(.van-field) {
    padding: 0;

    .van-field__control {
      min-height: 80px;
      padding: 12px;
      border: 1px solid #ebedf0;
      border-radius: 6px;
      font-size: 14px;
      line-height: 1.4;
      resize: none;

      &:focus {
        border-color: #1989fa;
      }
    }

    .van-field__word-limit {
      margin-top: 8px;
      text-align: right;
      font-size: 12px;
      color: #969799;
    }
  }
}

/* 附件列表样式 */
.attachments-list {
  margin-top: 8px;
}
.att-row {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f2f3f5;
}
.att-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 12px;
  box-sizing: border-box;
  background: #eef3fb;
  color: #1565c0;
}
.att-icon.img {
  background: #e8f5e9;
  color: #2e7d32;
}
.att-icon.pdf {
  background: #ffebee;
  color: #c62828;
}
.att-icon.docx {
  background: #e3f2fd;
  color: #1565c0;
}
.att-icon.xls {
  background: #e8f5e9;
  color: #1b5e20;
}
.att-name {
  flex: 1;
  font-size: 14px;
  color: #323233;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.empty-tip {
  padding: 12px 16px;
  color: #969799;
  font-size: 12px;
}
</style>